﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using VAdvantage.Controls;
using System.Data;
using System.Data.SqlClient;
using VAdvantage.Logging;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Windows.Threading;


namespace VAdvantage.Grids
{
    public class VCreateFromShipment : VCreateFrom
    {
        #region Private Variables
        private const long SERIALVERSIONUID = 1L;
        //Loaded Invoice             
        private MInvoice _invoice = null;
        //	Static Logger	
        private static VLogger _log = VLogger.GetVLogger(typeof(VCreateFromShipment).FullName);
        #endregion

        /// <summary>
        /// Protected Constructor
        /// </summary>
        /// <param name="mTab">MTab</param>
        public VCreateFromShipment(GridTab mTab)
            : base(mTab)
        {
            this.cmbInvoice.SelectionChanged += new SelectionChangedEventHandler(cmbInvoice_SelectionChanged);
            this.cmbOrder.SelectionChanged += new SelectionChangedEventHandler(cmbOrder_SelectionChanged);
        }


        /// <summary>
        /// Dynamic Init
        /// </summary>
        /// <returns>true if initialized</returns>
        protected override bool DynInit()
        {
            _log.Config("");
            this.Title = Msg.GetElement(Envs.GetContext(), "M_InOut_ID", false) + " .. " + Msg.Translate(Envs.GetContext(), "CreateFrom");
            lblShipment.Visible = false;
            cmbShipment.Visible = false;

            //  load Locator
            int AD_Column_ID = 3537;            //  M_InOut.M_Locator_ID
            MLocatorLookup locator = new MLocatorLookup(Envs.GetContext(), _WindowNo);
            locatorField = new VTextBoxButton("M_Locator_ID", true, false, true, DisplayType.Locator, locator, _WindowNo);
            InitBPartner(false);
            return true;
        }

        /// <summary>
        /// Get list of invoices for a particular business partner
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="C_BPartner_ID"></param>
        /// <param name="isReturnTrx"></param>
        /// <returns></returns>
        public static List<NamePair> GetInvoices(Context ctx, int C_BPartner_ID, bool isReturnTrx)
        {
            List<NamePair> pairs = new List<NamePair>();

            StringBuilder display = new StringBuilder("i.DocumentNo||' - '||").Append(
                    DB.TO_CHAR("DateInvoiced", DisplayType.Date, Envs.GetAD_Language(ctx))).Append("|| ' - ' ||")
                    .Append(DB.TO_CHAR("GrandTotal", DisplayType.Amount, Envs.GetAD_Language(ctx)));

            StringBuilder sql = new StringBuilder("SELECT i.C_Invoice_ID,").Append(display).Append(
                    " FROM C_Invoice i INNER JOIN C_DocType d ON (i.C_DocType_ID = d.C_DocType_ID) "
                            + "WHERE i.C_BPartner_ID=" + C_BPartner_ID + " AND i.IsSOTrx='N' "
                            + "AND d.IsReturnTrx='" + (isReturnTrx ? "Y" : "N") + "' "
                            + "AND i.DocStatus IN ('CL','CO')"
                            + " AND i.C_Invoice_ID IN " + "(SELECT il.C_Invoice_ID FROM C_InvoiceLine il"
                            + " LEFT OUTER JOIN M_MatchInv mi ON (il.C_InvoiceLine_ID=mi.C_InvoiceLine_ID) "
                            + "GROUP BY il.C_Invoice_ID,mi.C_InvoiceLine_ID,il.QtyInvoiced "
                            + "HAVING (il.QtyInvoiced<>SUM(mi.Qty) AND mi.C_InvoiceLine_ID IS NOT NULL)"
                            + " OR mi.C_InvoiceLine_ID IS NULL) " + "ORDER BY i.DateInvoiced");
            DataTable dt = null;
            IDataReader idr = null;
            try
            {
                idr = DB.ExecuteReader(sql.ToString(), null, null);
                dt = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)// while( dr.next() )
                {
                    pairs.Add(new KeyNamePair(Util.GetValueOfInt(dr[0].ToString()), dr[1].ToString()));
                }
            }
            catch (Exception e)
            {
                _log.Log(Level.SEVERE, sql.ToString(), e);
            }
            finally
            {
                dt = null;
                idr.Close();
            }
            return pairs;
        }

        /// <summary>
        /// Init Details - load invoices not shipped
        /// </summary>
        /// <param name="C_BPartner_ID">BPartner</param>
        protected override void InitBPDetails(int C_BPartner_ID, List<NamePair> invoices, List<NamePair> shipments)
        {
            _log.Config("C_BPartner_ID=" + C_BPartner_ID);
            //  load AP Invoice closed or complete
            cmbInvoice.Items.Clear();
            //	None
            KeyNamePair pp = new KeyNamePair(0, "");
            cmbInvoice.Items.Add(pp);

            // bool isReturnTrx = "Y".Equals(Envs.GetContext().GetContext(_WindowNo, "IsReturnTrx"));
            // ThreadPool.QueueUserWorkItem(delegate
            //{
            //    List<NamePair> invoices = GetInvoices(Envs.GetContext(), C_BPartner_ID, isReturnTrx);
            //    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(invoices));
            //});
            foreach (NamePair pair in invoices)
            {
                cmbInvoice.Items.Add(pair);
            }
            cmbInvoice.SelectedIndex = 0;


        }
        //private void InvoKFunction( List<NamePair> invoices)
        //{
        //    foreach (NamePair pair in invoices)
        //    {
        //        cmbInvoice.Items.Add(pair);
        //    }
        //    cmbInvoice.SelectedIndex = 0;
        //}
        /// <summary>
        /// Load Data - Invoice
        /// </summary>
        /// <param name="C_Invoice_ID">Invoice</param>
        private void LoadInvoice(int C_Invoice_ID)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                _invoice = new MInvoice(Envs.GetContext(), C_Invoice_ID, null);    //  save
                _order = null;
                //ArrayList data = GetInvoiceData(Envs.GetContext(), C_Invoice_ID);
                DataSet data = GetInvoiceData(Envs.GetContext(), C_Invoice_ID);
                // LoadTableOIS(data);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => BindGrid(data, 0, 0, true));

            });
        }

        /// <summary>
        /// Get the table data for a particular invoice
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="C_Invoice_ID"></param>
        /// <returns></returns>
        public static DataSet GetInvoiceData(Context ctx, int C_Invoice_ID)
        {
            _log.Config("C_Invoice_ID=" + C_Invoice_ID);
            StringBuilder sql = new StringBuilder("SELECT (l.QtyInvoiced-SUM(NVL(mi.Qty,0))) * " +
            " (l.QtyEntered       /l.QtyInvoiced) as QUANTITY     ," +
            " l.C_UOM_ID   AS C_UOM_ID                         ," +
            " COALESCE(uom.UOMSymbol,uom.Name)  AS UOM     ," +
            " l.M_Product_ID             AS M_PRODUCT_ID             ," +
            " p.Name               AS PRODUCT                   ," +
            " l.C_InvoiceLine_ID          AS C_INVOICELINE_ID          ," +
            " l.Line                         AS LINE        ," +
            " l.C_OrderLine_ID  AS C_ORDERLINE_ID,'false' as SELECTROW  ");                   					//  9
            //StringBuilder sql = new StringBuilder("SELECT (l.QtyInvoiced-SUM(NVL(mi.Qty,0))) * " +
            //                    " (l.QtyEntered       /l.QtyInvoiced ) as QUANTITY , " +
            //                    " l.C_UOM_ID   AS C_UOM_ID    , " +
            //                    " COALESCE(uom.UOMSymbol,uom.Name)  AS UOM , " +
            //                    " l.M_Product_ID          AS M_PRODUCT_ID , " +
            //                    " p.Name             AS PRODUCT     , " +
            //                    " l.C_InvoiceLine_ID   as C_INVOICELINE_ID  , " +
            //                    " l.Line              as LINE   , " +
            //                    " l.C_OrderLine_ID as C_ORDERLINE_ID ");
            if (Envs.IsBaseLanguage(ctx, "C_UOM"))
            {
                sql.Append("FROM C_UOM uom ")
                   .Append("INNER JOIN C_InvoiceLine l ON (l.C_UOM_ID=uom.C_UOM_ID) ");

            }
            else
            {
                sql.Append("FROM C_UOM_Trl uom ")
                   .Append("INNER JOIN C_InvoiceLine l ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='")
                   .Append(Envs.GetAD_Language(ctx)).Append("') ");
            }
            sql.Append("INNER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID) ")
               .Append("LEFT OUTER JOIN M_MatchInv mi ON (l.C_InvoiceLine_ID=mi.C_InvoiceLine_ID) ")
               .Append("WHERE l.C_Invoice_ID=" + C_Invoice_ID 									//  #1
                + " GROUP BY l.QtyInvoiced,l.QtyEntered/l.QtyInvoiced,"
                + "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"
                    + "l.M_Product_ID,p.Name, l.C_InvoiceLine_ID,l.Line,l.C_OrderLine_ID "
                + "ORDER BY l.Line");

            DataSet ds = DB.ExecuteDataset(sql.ToString(), null, null);
            return ds;
        }

        //public static ArrayList GetInvoiceData(Context ctx, int C_Invoice_ID)
        //{
        //    _log.Config("C_Invoice_ID=" + C_Invoice_ID);
        //    ArrayList data = new ArrayList();
        //    StringBuilder sql = new StringBuilder("SELECT "	//	Entered UOM
        //        + "l.QtyInvoiced-SUM(NVL(mi.Qty,0)),l.QtyEntered/l.QtyInvoiced,"
        //        + " l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"			//  3..4
        //        + " l.M_Product_ID,p.Name, l.C_InvoiceLine_ID,l.Line,"      //  5..8
        //        + " l.C_OrderLine_ID ");                   					//  9

        //    if (Envs.IsBaseLanguage(ctx, "C_UOM"))
        //    {
        //        sql.Append("FROM C_UOM uom ")
        //           .Append("INNER JOIN C_InvoiceLine l ON (l.C_UOM_ID=uom.C_UOM_ID) ");

        //    }
        //    else
        //    {
        //        sql.Append("FROM C_UOM_Trl uom ")
        //           .Append("INNER JOIN C_InvoiceLine l ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='")
        //           .Append(Envs.GetAD_Language(ctx)).Append("') ");
        //    }
        //    sql.Append("INNER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID) ")
        //       .Append("LEFT OUTER JOIN M_MatchInv mi ON (l.C_InvoiceLine_ID=mi.C_InvoiceLine_ID) ")
        //       .Append("WHERE l.C_Invoice_ID=" + C_Invoice_ID 									//  #1
        //        + "GROUP BY l.QtyInvoiced,l.QtyEntered/l.QtyInvoiced,"
        //        + "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"
        //            + "l.M_Product_ID,p.Name, l.C_InvoiceLine_ID,l.Line,l.C_OrderLine_ID "
        //        + "ORDER BY l.Line");
        //    DataTable dt = null;
        //    IDataReader idr = null;
        //    try
        //    {
        //        idr = DB.ExecuteReader(sql.ToString(), null, null);
        //        dt = new DataTable();
        //        dt.Load(idr);
        //        idr.Close();
        //        foreach (DataRow dr in dt.Rows)
        //        {
        //            ArrayList line = new ArrayList();
        //            line.Add(false);           //  0-Selection
        //            Decimal qtyInvoiced = Util.GetValueOfDecimal(dr[0]);//dr.getBigDecimal(1);
        //            Decimal multiplier = Util.GetValueOfDecimal(dr[1]);//dr.getBigDecimal(2);
        //            Decimal qtyEntered = Decimal.Multiply(qtyInvoiced, multiplier);
        //            line.Add(Convert.ToDouble(qtyEntered));//qtyEntered.doubleValue()));  //  1-Qty
        //            KeyNamePair pp = new KeyNamePair(Util.GetValueOfInt(dr[2].ToString()), dr[3].ToString().Trim());
        //            line.Add(pp);                           //  2-UOM
        //            pp = new KeyNamePair(Util.GetValueOfInt(dr[4].ToString()), dr[5].ToString());
        //            line.Add(pp);                           //  3-Product
        //            int C_OrderLine_ID = Util.GetValueOfInt(dr[8].ToString());//.getInt(9);
        //            if (dr == null)
        //            {
        //                line.Add(null);                     //  4-Order
        //            }
        //            else
        //            {
        //                line.Add(new KeyNamePair(C_OrderLine_ID, "."));
        //            }
        //            line.Add(null);                     	//  5-Ship
        //            pp = new KeyNamePair(Util.GetValueOfInt(dr[6].ToString()), dr[7].ToString());
        //            line.Add(pp);                           //  6-Invoice
        //            data.Add(line);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        _log.Log(Level.SEVERE, sql.ToString(), e);
        //    }
        //    finally
        //    {
        //        dt = null;
        //        idr.Close();
        //    }
        //    return data;
        //}

        /// <summary>
        /// List number of rows selected 
        /// to show message on status bar
        /// </summary>
        protected override void Info()
        {
            ////VDataGrid model = base.vdgvRecords;
            //DataSet ds = (DataSet)base.vdgvRecords.DataContext;
            //DataTable dt = ds.Tables[0];
            ////int rows = GlobalVariable.GridRowsCount(model);
            //int rows = dt.Rows.Count;
            //int count = 0;
            //for (int i = 0; i < rows; i++)
            //{
            //    //if (Convert.ToBoolean(Model.Rows[i].Cells[0].Value))
            //    if (Convert.ToBoolean(dt.Rows[i][0]))
            //    {
            //        count++;
            //    }
            //}
            ////statusBar.setStatusLine(String.valueOf(count));
            //base.statusBar.SetStatusDB(count.ToString());
            //gridCount = count;
        }

        /// <summary>
        /// Save - create Shipments
        /// </summary>
        /// <returns>true if saved</returns>
        protected override bool Save()
        {
            base.btnOk.IsEnabled = false;
            _log.Config("");
            // VDataGrid model = base.vdgvRecords;
           // IList list = base.vdgvRecords.SelectedItems;
            int loc = Convert.ToInt32(locatorField.GetValue());
            if (loc == null || loc == 0)
            {
                locatorField.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                ShowMessage.Info("LocatorFieldIsMandatory", null, "", "");
                return false;
            }
            int M_Locator_ID = loc;
            //	Get Shipment
            int M_InOut_ID = Convert.ToInt32(((int)_mTab.GetValue("M_InOut_ID")));
             ThreadPool.QueueUserWorkItem(delegate
            {
            SaveData(Envs.GetContext(), mainDataSet, _order, _invoice, M_Locator_ID, M_InOut_ID);
            Dispatcher.BeginInvoke(delegate
            {
                base.DialogResult = true;
            });
            });
             return true;
            //return SaveData(Envs.GetContext(), list, _order, _invoice, M_Locator_ID, M_InOut_ID);
        }

        /// <summary>
        /// Get ID
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        static int GetID(Object obj)
        {
            int id = 0;
            if (obj is KeyNamePair)
            {
                id = ((KeyNamePair)obj).GetKey();
            }
            else if (obj is int || obj is Decimal || obj is Double)
            {
                id = Convert.ToInt32(obj);
            }
            return id;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="model"></param>
        /// <param name="_order"></param>
        /// <param name="_invoice"></param>
        /// <param name="M_Locator_ID"></param>
        /// <param name="M_InOut_ID"></param>
        /// <returns></returns>
        public static bool SaveData(Context ctx, DataSet ds, MOrder _order, MInvoice _invoice, int M_Locator_ID, int M_InOut_ID)
        {
            // int rows = GlobalVariable.GridRowsCount(model);// Model.RowCount;
            List<DataRow> collection = new List<DataRow>();
            if (ds != null)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["SELECTROW"].ToString().ToUpper() == "TRUE")
                    {
                        collection.Add(ds.Tables[0].Rows[i]);
                    }
                }
            }
            else
            {
                return false;
            }

            //int rows = ds.Tables[0].Rows.Count;
            int rows = collection.Count;

            if (rows == 0)
            {
                return false;
            }


           
                MInOut inout = new MInOut(ctx, M_InOut_ID, null);
                //s_log.config(inout + ", C_Locator_ID=" + M_Locator_ID);

                /**
                 *  Selected        - 0
                 *  QtyEntered      - 1
                 *  C_UOM_ID        - 2
                 *  M_Product_ID    - 3
                 *  OrderLine       - 4
                 *  ShipmentLine    - 5
                 *  InvoiceLine     - 6
                 */

                //  Lines
                for (int i = 0; i < rows; i++)
                {
                    //if (Convert.ToBoolean(Model.Rows[i].Cells[0].Value))
                    if (true)//Convert.ToBoolean(((BindableObject)list[i]).GetValue("SELECT")))
                    {
                        //  variable values
                        double d = Convert.ToDouble(collection[i].ItemArray["QUANTITY"].Value);           //  1-Qty
                        //double d = Convert.ToDouble(((BindableObject)list[i]).GetValue("QUANTITY"));           //  1-Qty
                        Decimal QtyEntered = Convert.ToDecimal(d);//.doubleValue());
                        int C_UOM_ID = Util.GetValueOfInt(collection[i].ItemArray["C_UOM_ID"].Value);//.getValueAt(i, 2));   //  2-UOM
                        int M_Product_ID = Util.GetValueOfInt(collection[i].ItemArray["M_PRODUCT_ID"].Value);//.getValueAt(i, 3));               //  3-Product
                        int C_OrderLine_ID = 0;
                        int C_InvoiceLine_ID = 0;
                        try
                        {
                            C_OrderLine_ID = Util.GetValueOfInt(collection[i].ItemArray["C_ORDERLINE_ID"].Value);//.getValueAt(i, 4));               //  4-OrderLine
                            C_InvoiceLine_ID = Util.GetValueOfInt(collection[i].ItemArray["C_INVOICELINE_ID"].Value);//.getValueAt(i, 6));               //  6-InvoiceLine
                        }
                        catch (Exception ex)
                        {
                            _log.SaveError("ColumnNotFound", ex);
                        }
                        MInvoiceLine il = null;
                        if (C_InvoiceLine_ID != 0)
                        {
                            il = new MInvoiceLine(ctx, C_InvoiceLine_ID, null);
                        }
                        bool isInvoiced = (C_InvoiceLine_ID != 0);
                        //	Precision of Qty UOM
                        int precision = 2;
                        if (M_Product_ID != 0)
                        {
                            MProduct product = MProduct.Get(ctx, M_Product_ID);
                            precision = product.GetUOMPrecision();
                        }
                        QtyEntered = Decimal.Round(QtyEntered, precision);
                        _log.Fine("Line QtyEntered=" + QtyEntered
                                + ", UOM=" + C_UOM_ID
                            + ", Product=" + M_Product_ID
                            + ", OrderLine=" + C_OrderLine_ID + ", InvoiceLine=" + C_InvoiceLine_ID);

                        //	Create new InOut Line
                        MInOutLine iol = new MInOutLine(inout);
                        iol.SetM_Product_ID(M_Product_ID, C_UOM_ID);	//	Line UOM
                        iol.SetQty(QtyEntered);							//	Movement/Entered
                        //
                        MOrderLine ol = null;
                        if (C_OrderLine_ID != 0)
                        {
                            iol.SetC_OrderLine_ID(C_OrderLine_ID);
                            ol = new MOrderLine(ctx, C_OrderLine_ID, null);
                            if (ol.GetQtyEntered().CompareTo(ol.GetQtyOrdered()) != 0)
                            {
                                iol.SetMovementQty(Decimal.Round(Decimal.Divide(Decimal.Multiply(QtyEntered, ol.GetQtyOrdered()), ol.GetQtyEntered()), 12));
                                iol.SetC_UOM_ID(ol.GetC_UOM_ID());
                            }
                            iol.SetM_AttributeSetInstance_ID(ol.GetM_AttributeSetInstance_ID());
                            iol.SetDescription(ol.GetDescription());
                            iol.SetC_Project_ID(ol.GetC_Project_ID());
                            iol.SetC_ProjectPhase_ID(ol.GetC_ProjectPhase_ID());
                            iol.SetC_ProjectTask_ID(ol.GetC_ProjectTask_ID());
                            iol.SetC_Activity_ID(ol.GetC_Activity_ID());
                            iol.SetC_Campaign_ID(ol.GetC_Campaign_ID());
                            iol.SetAD_OrgTrx_ID(ol.GetAD_OrgTrx_ID());
                            iol.SetUser1_ID(ol.GetUser1_ID());
                            iol.SetUser2_ID(ol.GetUser2_ID());
                        }
                        else if (il != null)
                        {
                            if (il.GetQtyEntered().CompareTo(il.GetQtyInvoiced()) != 0)
                            {
                                iol.SetQtyEntered(Decimal.Round(Decimal.Divide(Decimal.Multiply(QtyEntered, il.GetQtyInvoiced()), il.GetQtyEntered()), 12));
                                iol.SetC_UOM_ID(il.GetC_UOM_ID());
                            }
                            iol.SetDescription(il.GetDescription());
                            iol.SetC_Project_ID(il.GetC_Project_ID());
                            iol.SetC_ProjectPhase_ID(il.GetC_ProjectPhase_ID());
                            iol.SetC_ProjectTask_ID(il.GetC_ProjectTask_ID());
                            iol.SetC_Activity_ID(il.GetC_Activity_ID());
                            iol.SetC_Campaign_ID(il.GetC_Campaign_ID());
                            iol.SetAD_OrgTrx_ID(il.GetAD_OrgTrx_ID());
                            iol.SetUser1_ID(il.GetUser1_ID());
                            iol.SetUser2_ID(il.GetUser2_ID());
                        }
                        //	Charge
                        if (M_Product_ID == 0)
                        {
                            if (ol != null && ol.GetC_Charge_ID() != 0)			//	from order
                            {
                                iol.SetC_Charge_ID(ol.GetC_Charge_ID());
                            }
                            else if (il != null && il.GetC_Charge_ID() != 0)	//	from invoice
                            {
                                iol.SetC_Charge_ID(il.GetC_Charge_ID());
                            }
                        }
                        iol.SetM_Locator_ID(M_Locator_ID);
                        if (!iol.Save())
                        {
                            _log.Log(Level.SEVERE, "Line NOT created #" + i);
                        }
                        //	Create Invoice Line Link
                        else if (il != null)
                        {
                            il.SetM_InOutLine_ID(iol.GetM_InOutLine_ID());
                            il.Save();
                        }
                    }   //   if selected
                }   //  for all rows

                /**
                 *  Update Header
                 *  - if linked to another order/invoice - remove link
                 *  - if no link set it
                 */
                if (_order != null && _order.GetC_Order_ID() != 0)
                {
                    inout.SetC_Order_ID(_order.GetC_Order_ID());
                    inout.SetAD_OrgTrx_ID(_order.GetAD_OrgTrx_ID());
                    inout.SetC_Project_ID(_order.GetC_Project_ID());
                    inout.SetC_Campaign_ID(_order.GetC_Campaign_ID());
                    inout.SetC_Activity_ID(_order.GetC_Activity_ID());
                    inout.SetUser1_ID(_order.GetUser1_ID());
                    inout.SetUser2_ID(_order.GetUser2_ID());
                }
                if (_invoice != null && _invoice.GetC_Invoice_ID() != 0)
                {
                    if (inout.GetC_Order_ID() == 0)
                    {
                        inout.SetC_Order_ID(_invoice.GetC_Order_ID());
                    }
                    inout.SetC_Invoice_ID(_invoice.GetC_Invoice_ID());
                    inout.SetAD_OrgTrx_ID(_invoice.GetAD_OrgTrx_ID());
                    inout.SetC_Project_ID(_invoice.GetC_Project_ID());
                    inout.SetC_Campaign_ID(_invoice.GetC_Campaign_ID());
                    inout.SetC_Activity_ID(_invoice.GetC_Activity_ID());
                    inout.SetUser1_ID(_invoice.GetUser1_ID());
                    inout.SetUser2_ID(_invoice.GetUser2_ID());
                }
                inout.Save();
               
           // });
            return true;
        }

        //public static bool SaveData(Context ctx, IList list, MOrder _order, MInvoice _invoice, int M_Locator_ID, int M_InOut_ID)
        //{
        //    // int rows = GlobalVariable.GridRowsCount(model);// Model.RowCount;
        //    int rows = list.Count;
        //    if (rows == 0)
        //    {
        //        return false;
        //    }

        //    ThreadPool.QueueUserWorkItem(delegate
        //  {
        //      MInOut inout = new MInOut(ctx, M_InOut_ID, null);
        //      //s_log.config(inout + ", C_Locator_ID=" + M_Locator_ID);

        //      /**
        //       *  Selected        - 0
        //       *  QtyEntered      - 1
        //       *  C_UOM_ID        - 2
        //       *  M_Product_ID    - 3
        //       *  OrderLine       - 4
        //       *  ShipmentLine    - 5
        //       *  InvoiceLine     - 6
        //       */

        //      //  Lines
        //      for (int i = 0; i < rows; i++)
        //      {
        //          //if (Convert.ToBoolean(Model.Rows[i].Cells[0].Value))
        //          if (true)//Convert.ToBoolean(((BindableObject)list[i]).GetValue("SELECT")))
        //          {
        //              //  variable values
        //              //Number d = (Number)Model.getValueAt(i, 1);              //  1-Qty
        //              double d = Convert.ToDouble(((BindableObject)list[i]).GetValue("QUANTITY"));           //  1-Qty
        //              Decimal QtyEntered = Convert.ToDecimal(d);//.doubleValue());
        //              int C_UOM_ID = Util.GetValueOfInt(((BindableObject)list[i]).GetValue("C_UOM_ID"));//.getValueAt(i, 2));   //  2-UOM
        //              int M_Product_ID = Util.GetValueOfInt(((BindableObject)list[i]).GetValue("M_PRODUCT_ID"));//.getValueAt(i, 3));               //  3-Product
        //              int C_OrderLine_ID = Util.GetValueOfInt(((BindableObject)list[i]).GetValue("C_ORDERLINE_ID"));//.getValueAt(i, 4));               //  4-OrderLine
        //              int C_InvoiceLine_ID = Util.GetValueOfInt(((BindableObject)list[i]).GetValue("C_INVOICELINE_ID"));//.getValueAt(i, 6));               //  6-InvoiceLine
        //              MInvoiceLine il = null;
        //              if (C_InvoiceLine_ID != 0)
        //              {
        //                  il = new MInvoiceLine(ctx, C_InvoiceLine_ID, null);
        //              }
        //              bool isInvoiced = (C_InvoiceLine_ID != 0);
        //              //	Precision of Qty UOM
        //              int precision = 2;
        //              if (M_Product_ID != 0)
        //              {
        //                  MProduct product = MProduct.Get(ctx, M_Product_ID);
        //                  precision = product.GetUOMPrecision();
        //              }
        //              QtyEntered = Decimal.Round(QtyEntered, precision);
        //              _log.Fine("Line QtyEntered=" + QtyEntered
        //                      + ", UOM=" + C_UOM_ID
        //                  + ", Product=" + M_Product_ID
        //                  + ", OrderLine=" + C_OrderLine_ID + ", InvoiceLine=" + C_InvoiceLine_ID);

        //              //	Create new InOut Line
        //              MInOutLine iol = new MInOutLine(inout);
        //              iol.SetM_Product_ID(M_Product_ID, C_UOM_ID);	//	Line UOM
        //              iol.SetQty(QtyEntered);							//	Movement/Entered
        //              //
        //              MOrderLine ol = null;
        //              if (C_OrderLine_ID != 0)
        //              {
        //                  iol.SetC_OrderLine_ID(C_OrderLine_ID);
        //                  ol = new MOrderLine(ctx, C_OrderLine_ID, null);
        //                  if (ol.GetQtyEntered().CompareTo(ol.GetQtyOrdered()) != 0)
        //                  {
        //                      iol.SetMovementQty(Decimal.Round(Decimal.Divide(Decimal.Multiply(QtyEntered, ol.GetQtyOrdered()), ol.GetQtyEntered()), 12));
        //                      iol.SetC_UOM_ID(ol.GetC_UOM_ID());
        //                  }
        //                  iol.SetM_AttributeSetInstance_ID(ol.GetM_AttributeSetInstance_ID());
        //                  iol.SetDescription(ol.GetDescription());
        //                  iol.SetC_Project_ID(ol.GetC_Project_ID());
        //                  iol.SetC_ProjectPhase_ID(ol.GetC_ProjectPhase_ID());
        //                  iol.SetC_ProjectTask_ID(ol.GetC_ProjectTask_ID());
        //                  iol.SetC_Activity_ID(ol.GetC_Activity_ID());
        //                  iol.SetC_Campaign_ID(ol.GetC_Campaign_ID());
        //                  iol.SetAD_OrgTrx_ID(ol.GetAD_OrgTrx_ID());
        //                  iol.SetUser1_ID(ol.GetUser1_ID());
        //                  iol.SetUser2_ID(ol.GetUser2_ID());
        //              }
        //              else if (il != null)
        //              {
        //                  if (il.GetQtyEntered().CompareTo(il.GetQtyInvoiced()) != 0)
        //                  {
        //                      iol.SetQtyEntered(Decimal.Round(Decimal.Divide(Decimal.Multiply(QtyEntered, il.GetQtyInvoiced()), il.GetQtyEntered()), 12));
        //                      iol.SetC_UOM_ID(il.GetC_UOM_ID());
        //                  }
        //                  iol.SetDescription(il.GetDescription());
        //                  iol.SetC_Project_ID(il.GetC_Project_ID());
        //                  iol.SetC_ProjectPhase_ID(il.GetC_ProjectPhase_ID());
        //                  iol.SetC_ProjectTask_ID(il.GetC_ProjectTask_ID());
        //                  iol.SetC_Activity_ID(il.GetC_Activity_ID());
        //                  iol.SetC_Campaign_ID(il.GetC_Campaign_ID());
        //                  iol.SetAD_OrgTrx_ID(il.GetAD_OrgTrx_ID());
        //                  iol.SetUser1_ID(il.GetUser1_ID());
        //                  iol.SetUser2_ID(il.GetUser2_ID());
        //              }
        //              //	Charge
        //              if (M_Product_ID == 0)
        //              {
        //                  if (ol != null && ol.GetC_Charge_ID() != 0)			//	from order
        //                  {
        //                      iol.SetC_Charge_ID(ol.GetC_Charge_ID());
        //                  }
        //                  else if (il != null && il.GetC_Charge_ID() != 0)	//	from invoice
        //                  {
        //                      iol.SetC_Charge_ID(il.GetC_Charge_ID());
        //                  }
        //              }
        //              iol.SetM_Locator_ID(M_Locator_ID);
        //              if (!iol.Save())
        //              {
        //                  _log.Log(Level.SEVERE, "Line NOT created #" + i);
        //              }
        //              //	Create Invoice Line Link
        //              else if (il != null)
        //              {
        //                  il.SetM_InOutLine_ID(iol.GetM_InOutLine_ID());
        //                  il.Save();
        //              }
        //          }   //   if selected
        //      }   //  for all rows

        //      /**
        //       *  Update Header
        //       *  - if linked to another order/invoice - remove link
        //       *  - if no link set it
        //       */
        //      if (_order != null && _order.GetC_Order_ID() != 0)
        //      {
        //          inout.SetC_Order_ID(_order.GetC_Order_ID());
        //          inout.SetAD_OrgTrx_ID(_order.GetAD_OrgTrx_ID());
        //          inout.SetC_Project_ID(_order.GetC_Project_ID());
        //          inout.SetC_Campaign_ID(_order.GetC_Campaign_ID());
        //          inout.SetC_Activity_ID(_order.GetC_Activity_ID());
        //          inout.SetUser1_ID(_order.GetUser1_ID());
        //          inout.SetUser2_ID(_order.GetUser2_ID());
        //      }
        //      if (_invoice != null && _invoice.GetC_Invoice_ID() != 0)
        //      {
        //          if (inout.GetC_Order_ID() == 0)
        //          {
        //              inout.SetC_Order_ID(_invoice.GetC_Order_ID());
        //          }
        //          inout.SetC_Invoice_ID(_invoice.GetC_Invoice_ID());
        //          inout.SetAD_OrgTrx_ID(_invoice.GetAD_OrgTrx_ID());
        //          inout.SetC_Project_ID(_invoice.GetC_Project_ID());
        //          inout.SetC_Campaign_ID(_invoice.GetC_Campaign_ID());
        //          inout.SetC_Activity_ID(_invoice.GetC_Activity_ID());
        //          inout.SetUser1_ID(_invoice.GetUser1_ID());
        //          inout.SetUser2_ID(_invoice.GetUser2_ID());
        //      }
        //      inout.Save();
        //  });
        //    return true;
        //}

        void cmbOrder_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //vdgvRecords.Rows.Clear();
            vdgvRecords.DataContext = null;
            vdgvRecords.ItemsSource = null;
            vdgvRecords.Columns.Clear();
            KeyNamePair pp = (KeyNamePair)cmbOrder.SelectedItem;
            if (pp == null || pp.GetKey() == 0)
            {
                ;
            }
            else
            {
                int C_Order_ID = pp.GetKey();
                //  set Invoice and Shipment to Null
                cmbInvoice.SelectedIndex = -1;
                cmbShipment.SelectedIndex = -1;
                LoadOrder(C_Order_ID, false);
                _invoice = null;
            }

        }

        void cmbInvoice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //vdgvRecords.Rows.Clear();
            vdgvRecords.DataContext = null;
            vdgvRecords.ItemsSource = null;
            vdgvRecords.Columns.Clear();
            KeyNamePair pp = (KeyNamePair)cmbInvoice.SelectedItem;
            if (pp == null || pp.GetKey() == 0)
            {
                ;
            }
            else
            {
                int C_Invoice_ID = pp.GetKey();
                //  set Order and Shipment to Null
                cmbOrder.SelectedIndex = -1;
                cmbShipment.SelectedIndex = -1;
                LoadInvoice(C_Invoice_ID);
            }
        }
    }
}
